home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 2000 August: Tool Chest / Dev.CD Aug 00 TC Disk 2.toast / pc / sample code / human interface toolbox / password / sample.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-06-23  |  25.5 KB  |  719 lines

  1. /*
  2.     File:        Sample.c
  3.  
  4.     Contains:    This is just a hacked version of CSample.  Ignore any bits referring to the
  5.                 traffic lights, etc.
  6.  
  7.     Written by:     
  8.  
  9.     Copyright:    Copyright © 1999 by Apple Computer, Inc., All Rights Reserved.
  10.  
  11.                 You may incorporate this Apple sample source code into your program(s) without
  12.                 restriction. This Apple sample source code has been provided "AS IS" and the
  13.                 responsibility for its operation is yours. You are not permitted to redistribute
  14.                 this Apple sample source code as "Apple sample source code" after having made
  15.                 changes. If you're going to re-distribute the source, we require that you make
  16.                 it clear in the source that the code was descended from Apple sample source
  17.                 code, but that you've made changes.
  18.  
  19.     Change History (most recent first):
  20.                 8/9/1999    Karl Groethe    Updated for Metrowerks Codewarror Pro 2.1
  21.                 9/13/96     PG                 brought code into 20th century.
  22.  
  23. */
  24. #include <Types.h>
  25. #include <Resources.h>
  26. #include <QuickDraw.h>
  27. #include <Fonts.h>
  28. #include <Events.h>
  29. #include <Windows.h>
  30. #include <Menus.h>
  31. #include <TextEdit.h>
  32. #include <Dialogs.h>
  33. #include <Desk.h>
  34. #include <ToolUtils.h>
  35. #include <Memory.h>
  36. #include <SegLoad.h>
  37. #include <Files.h>
  38. #include <OSUtils.h>
  39. #include <OSEvents.h>
  40. #include <DiskInit.h>
  41. #include <Packages.h>
  42. #include <Traps.h>
  43. #include <Limits.h>
  44. #include <Processes.h>
  45. #include "Sample.h"        /* bring in all the #defines for Sample */
  46.  
  47. #include "Password.h"
  48.  
  49. /* The "g" prefix is used to emphasize that a variable is global. */
  50.  
  51. /* GMac is used to hold the result of a SysEnvirons call. This makes
  52.    it convenient for any routine to check the environment. */
  53. SysEnvRec    gMac;                /* set up by Initialize */
  54.  
  55. /* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  56.    trap is available. If it is false, we know that we must call GetNextEvent. */
  57. Boolean        gHasWaitNextEvent;    /* set up by Initialize */
  58.  
  59. /* GInBackground is maintained by our osEvent handling routines. Any part of
  60.    the program can check it to find out if it is currently in the background. */
  61. Boolean        gInBackground;        /* maintained by Initialize and DoEvent */
  62.  
  63.  
  64. /* The following globals are the state of the window. If we supported more than
  65.    one window, they would be attatched to each document, rather than globals. */
  66.  
  67. /* Define HiWrd and LoWrd macros for efficiency. */
  68. #define HiWrd(aLong)    (((aLong) >> 16) & 0xFFFF)
  69. #define LoWrd(aLong)    ((aLong) & 0xFFFF)
  70.  
  71. /* Define TopLeft and BotRight macros for convenience. Notice the implicit
  72.    dependency on the ordering of fields within a Rect */
  73. #define TopLeft(aRect)    (* (Point *) &(aRect).top)
  74. #define BotRight(aRect)    (* (Point *) &(aRect).bottom)
  75.  
  76. #ifdef applec
  77.     /* This routine is part of the MPW runtime library. This external
  78.            reference to it is done so that we can unload its segment, %A5Init. */
  79.  
  80.     extern void _DataInit();
  81. #endif
  82.  
  83. /*    Display an alert that tells the user an error occurred, then exit the program.
  84.     This routine is used as an ultimate bail-out for serious errors that prohibit
  85.     the continuation of the application. Errors that do not require the termination
  86.     of the application should be handled in a different manner. Error checking and
  87.     reporting has a place even in the simplest application. The error number is used
  88.     to index an 'STR#' resource so that a relevant message can be displayed. */
  89.  
  90. #pragma segment Main
  91. static void AlertUser(void)
  92. {
  93.     short        itemHit;
  94.  
  95.     SetCursor(&qd.arrow);
  96.     itemHit = Alert(rUserAlert, nil);
  97.     ExitToShell();
  98. } /* AlertUser */
  99.  
  100. /*    Check to see if a given trap is implemented. This is only used by the
  101.     Initialize routine in this program, so we put it in the Initialize segment.
  102.     The recommended approach to see if a trap is implemented is to see if
  103.     the address of the trap routine is the same as the address of the
  104.     Unimplemented trap. */
  105. /*    1.02 - Needs to be called after call to SysEnvirons so that it can check
  106.     if a ToolTrap is out of range of a pre-MacII ROM. */
  107.  
  108. #pragma segment Initialize
  109. // check to see if a given trap is implemented. We follow IM VI-3-8.
  110.  
  111. static Boolean TrapAvailable(short theTrap)
  112. {
  113.     TrapType theTrapType;
  114.     short numToolboxTraps;
  115.     
  116.     if ((theTrap & 0x0800) > 0)
  117.         theTrapType = ToolTrap;
  118.     else
  119.         theTrapType = OSTrap;
  120.  
  121.     if (theTrapType == ToolTrap)
  122.     {
  123.         theTrap = theTrap & 0x07ff;
  124.         if (NGetTrapAddress(_InitGraf, ToolTrap) == NGetTrapAddress(0xaa6e, ToolTrap))
  125.             numToolboxTraps = 0x0200;
  126.         else
  127.             numToolboxTraps = 0x0400;
  128.         if (theTrap >= numToolboxTraps)
  129.             theTrap = _Unimplemented;
  130.     };
  131.  
  132.     return (NGetTrapAddress(theTrap, theTrapType) != NGetTrapAddress(_Unimplemented, ToolTrap));
  133. }
  134.  
  135. /*    Set up the whole world, including global variables, Toolbox managers,
  136.     and menus. We also create our one application window at this time.
  137.     Since window storage is non-relocateable, how and when to allocate space
  138.     for windows is very important so that heap fragmentation does not occur.
  139.     Because Sample has only one window and it is only disposed when the application
  140.     quits, we will allocate its space here, before anything that might be a locked
  141.     relocatable object gets into the heap. This way, we can force the storage to be
  142.     in the lowest memory available in the heap. Window storage can differ widely
  143.     amongst applications depending on how many windows are created and disposed. */
  144.  
  145. /*    1.01 - The code that used to be part of ForceEnvirons has been moved into
  146.     this module. If an error is detected, instead of merely doing an ExitToShell,
  147.     which leaves the user without much to go on, we call AlertUser, which puts
  148.     up a simple alert that just says an error occurred and then calls ExitToShell.
  149.     Since there is no other cleanup needed at this point if an error is detected,
  150.     this form of error- handling is acceptable. If more sophisticated error recovery
  151.     is needed, an exception mechanism, such as is provided by Signals, can be used. */
  152.  
  153. #pragma segment Initialize
  154. static void Initialize (void)
  155. {    Handle        menuBar;
  156.     long        total, contig;
  157.     EventRecord event;
  158.     short        count;
  159.  
  160.     gInBackground = false;
  161.  
  162.     InitGraf((Ptr) &qd.thePort);
  163.     InitFonts();
  164.     InitWindows();
  165.     InitMenus();
  166.     TEInit();
  167.     InitDialogs(nil);
  168.     InitCursor();
  169.     
  170.     /*    Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
  171.          if you are using it. */
  172.     /*    NOTE -- It is no longer necessary, and actually unhealthy, to check
  173.         PortBUse and SPConfig before opening AppleTalk. The drivers are capable
  174.         of checking for port availability themselves. */
  175.     
  176.     /*    This next bit of code is necessary to allow the default button of our
  177.         alert be outlined.
  178.         1.02 - Changed to call EventAvail so that we don't lose some important
  179.         events. */
  180.      
  181.     for (count = 1; count <= 3; count++)
  182.         EventAvail(everyEvent, &event);
  183.     
  184.     /*    Ignore the error returned from SysEnvirons; even if an error occurred,
  185.         the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  186.         call to SysEnvirons by calling it after initializing AppleTalk. */
  187.      
  188.     SysEnvirons(kSysEnvironsVersion, &gMac);
  189.     
  190.     /* Make sure that the machine has at least 128K ROMs. If it doesn't, exit. */
  191.     
  192.     if (gMac.machineType < 0) AlertUser();
  193.     
  194.     /*    1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
  195.         in TrapAvailable if a tool trap value is out of range. */
  196.         
  197.     gHasWaitNextEvent = TrapAvailable(_WaitNextEvent);
  198.  
  199.     /*    1.01 - We used to make a check for memory at this point by examining ApplLimit,
  200.         ApplicationZone, and StackSpace and comparing that to the minimum size we told
  201.         MultiFinder we needed. This did not work well because it assumed too much about
  202.         the relationship between what we asked MultiFinder for and what we would actually
  203.         get back, as well as how to measure it. Instead, we will use an alternate
  204.         method comprised of two steps. */
  205.      
  206.     /*    It is better to first check the size of the application heap against a value
  207.         that you have determined is the smallest heap the application can reasonably
  208.         work in. This number should be derived by examining the size of the heap that
  209.         is actually provided by MultiFinder when the minimum size requested is used.
  210.         The derivation of the minimum size requested from MultiFinder is described
  211.         in Sample.h. The check should be made because the preferred size can end up
  212.         being set smaller than the minimum size by the user. This extra check acts to
  213.         insure that your application is starting from a solid memory foundation. */
  214.      
  215.     if ((long) GetApplLimit() - (long) ApplicationZone() < kMinHeap) AlertUser();
  216.     
  217.     /*    Next, make sure that enough memory is free for your application to run. It
  218.         is possible for a situation to arise where the heap may have been of required
  219.         size, but a large scrap was loaded which left too little memory. To check for
  220.         this, call PurgeSpace and compare the result with a value that you have determined
  221.         is the minimum amount of free memory your application needs at initialization.
  222.         This number can be derived several different ways. One way that is fairly
  223.         straightforward is to run the application in the minimum size configuration
  224.         as described previously. Call PurgeSpace at initialization and examine the value
  225.         returned. However, you should make sure that this result is not being modified
  226.         by the scrap's presence. You can do that by calling ZeroScrap before calling
  227.         PurgeSpace. Make sure to remove that call before shipping, though. */
  228.     
  229.     /* ZeroScrap(); */
  230.  
  231.     PurgeSpace(&total, &contig);
  232.     if (total < kMinSpace) AlertUser();
  233.  
  234.     /*    The extra benefit to waiting until after the Toolbox Managers have been initialized
  235.         to check memory is that we can now give the user an alert to tell him/her what
  236.         happened. Although it is possible that the memory situation could be worsened by
  237.         displaying an alert, MultiFinder would gracefully exit the application with
  238.         an informative alert if memory became critical. Here we are acting more
  239.         in a preventative manner to avoid future disaster from low-memory problems. */
  240.  
  241.     menuBar = GetNewMBar(rMenuBar);            /* read menus into menu bar */
  242.     if ( menuBar == nil ) AlertUser();
  243.     SetMenuBar(menuBar);                    /* install menus */
  244.     DisposeHandle(menuBar);
  245.     AppendResMenu(GetMenuHandle(mApple), 'DRVR');    /* add DA names to Apple menu */
  246.     DrawMenuBar();
  247.     
  248. } /*Initialize*/
  249.  
  250. /*    Get the global coordinates of the mouse. When you call OSEventAvail
  251.     it will return either a pending event or a null event. In either case,
  252.     the where field of the event record will contain the current position
  253.     of the mouse in global coordinates and the modifiers field will reflect
  254.     the current state of the modifiers. Another way to get the global
  255.     coordinates is to call GetMouse and LocalToGlobal, but that requires
  256.     being sure that thePort is set to a valid port. */
  257.  
  258. #pragma segment Main
  259. static void GetGlobalMouse (Point *mouse)
  260. {
  261.     EventRecord    event;
  262.     
  263.     OSEventAvail(kNoEvents, &event);    /* we aren't interested in any events */
  264.     *mouse = event.where;                /* just the mouse position */
  265. } /*GetGlobalMouse*/
  266.  
  267. /* Check to see if a window belongs to a desk accessory. */
  268.  
  269. #pragma segment Main
  270. static Boolean IsDAWindow (WindowPtr    window)
  271. {
  272.     if ( window == nil )
  273.         return false;
  274.     else    /* DA windows have negative windowKinds */
  275.         return ( ((WindowPeek) window)->windowKind < 0 );
  276. } /*IsDAWindow*/
  277.  
  278. /*    Check to see if a window belongs to the application. If the window pointer
  279.     passed was NIL, then it could not be an application window. WindowKinds
  280.     that are negative belong to the system and windowKinds less than userKind
  281.     are reserved by Apple except for windowKinds equal to dialogKind, which
  282.     mean it is a dialog.
  283.     1.02 - In order to reduce the chance of accidentally treating some window
  284.     as an AppWindow that shouldn't be, we'll only return true if the windowkind
  285.     is userKind. If you add different kinds of windows to Sample you'll need
  286.     to change how this all works. */
  287.  
  288. #pragma segment Main
  289. static Boolean IsAppWindow (WindowPtr    window)
  290. {
  291.     short        windowKind;
  292.  
  293.     if ( window == nil )
  294.         return false;
  295.     else {    /* application windows have windowKinds = userKind (8) */
  296.         windowKind = ((WindowPeek) window)->windowKind;
  297.         return ( windowKind == userKind );
  298.     }
  299. } /*IsAppWindow*/
  300.  
  301. /*    Change the cursor's shape, depending on its position. This also calculates the region
  302.     where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  303.     that region, an event would be generated, causing this routine to be called,
  304.     allowing us to change the region to the region the mouse is currently in. If
  305.     there is more to the event than just “the mouse moved”, we get called before the
  306.     event is processed to make sure the cursor is the right one. In any (ahem) event,
  307.     this is called again before we     fall back into WNE. */
  308.  
  309. #pragma segment Main
  310. static void AdjustCursor(Point mouse, RgnHandle region)
  311. {
  312.     WindowPtr    window;
  313.     RgnHandle    arrowRgn;
  314.     RgnHandle    plusRgn;
  315.     Rect        globalPortRect;
  316.  
  317.     window = FrontWindow();    /* we only adjust the cursor when we are in front */
  318.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  319.         /* calculate regions for different cursor shapes */
  320.         arrowRgn = NewRgn();
  321.         plusRgn = NewRgn();
  322.  
  323.         /* start with a big, big rectangular region */
  324.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
  325.  
  326.         /* calculate plusRgn */
  327.         if ( IsAppWindow(window) ) {
  328.             SetPort(window);    /* make a global version of the viewRect */
  329.             SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
  330.             globalPortRect = window->portRect;
  331.             RectRgn(plusRgn, &globalPortRect);
  332.             SectRgn(plusRgn, window->visRgn, plusRgn);
  333.             SetOrigin(0, 0);
  334.         }
  335.  
  336.         /* subtract other regions from arrowRgn */
  337.         DiffRgn(arrowRgn, plusRgn, arrowRgn);
  338.  
  339.         /* change the cursor and the region parameter */
  340.         if ( PtInRgn(mouse, plusRgn) ) {
  341.             SetCursor(*GetCursor(plusCursor));
  342.             CopyRgn(plusRgn, region);
  343.         } else {
  344.             SetCursor(&qd.arrow);
  345.             CopyRgn(arrowRgn, region);
  346.         }
  347.  
  348.         /* get rid of our local regions */
  349.         DisposeRgn(arrowRgn);
  350.         DisposeRgn(plusRgn);
  351.     }
  352. } /*AdjustCursor*/
  353.  
  354. /*    Enable and disable menus based on the current state.
  355.     The user can only select enabled menu items. We set up all the menu items
  356.     before calling MenuSelect or MenuKey, since these are the only times that
  357.     a menu item can be selected. Note that MenuSelect is also the only time
  358.     the user will see menu items. This approach to deciding what enable/
  359.     disable state a menu item has the advantage of concentrating all
  360.     the decision-making in one routine, as opposed to being spread throughout
  361.     the application. Other application designs may take a different approach
  362.     that is just as valid. */
  363.  
  364. #pragma segment Main
  365. static void AdjustMenus (void)
  366. {
  367.     WindowPtr    window;
  368.     MenuHandle    menu;
  369.  
  370.     window = FrontWindow();
  371.  
  372.     menu = GetMenuHandle(mFile);
  373.     if ( IsDAWindow(window) )        /* we can allow desk accessories to be closed from the menu */
  374.         EnableItem(menu, iClose);
  375.     else
  376.         DisableItem(menu, iClose);    /* but not our traffic light window */
  377.  
  378.     menu = GetMenuHandle(mEdit);
  379.     if ( IsDAWindow(window) ) {        /* a desk accessory might need the edit menu… */
  380.         EnableItem(menu, iUndo);
  381.         EnableItem(menu, iCut);
  382.         EnableItem(menu, iCopy);
  383.         EnableItem(menu, iClear);
  384.         EnableItem(menu, iPaste);
  385.     } else {                        /* …but we don’t use it */
  386.         DisableItem(menu, iUndo);
  387.         DisableItem(menu, iCut);
  388.         DisableItem(menu, iCopy);
  389.         DisableItem(menu, iClear);
  390.         DisableItem(menu, iPaste);
  391.     }
  392.     
  393.     menu = GetMenuHandle(mPassword);
  394.         EnableItem(menu, iTwoItem);
  395.         EnableItem(menu, iDifferentFont);
  396.         EnableItem(menu, iInternalBuffer);
  397.     
  398. } /*AdjustMenus*/
  399.  
  400. /* Close a window. This handles desk accessory and application windows. */
  401.  
  402. /*    1.01 - At this point, if there was a document associated with a
  403.     window, you could do any document saving processing if it is 'dirty'.
  404.     DoCloseWindow would return true if the window actually closed, i.e.,
  405.     the user didn’t cancel from a save dialog. This result is handy when
  406.     the user quits an application, but then cancels the save of a document
  407.     associated with a window. */
  408.  
  409. #pragma segment Main
  410. static Boolean DoCloseWindow (WindowPtr    window)
  411. {
  412.     if ( IsDAWindow(window) )
  413.         CloseDeskAcc(((WindowPeek) window)->windowKind);
  414.     else if ( IsAppWindow(window) )
  415.         CloseWindow(window);
  416.     return true;
  417. } /*DoCloseWindow*/
  418.  
  419. /* Clean up the application and exit. We close all of the windows so that
  420.  they can update their documents, if any. */
  421.  
  422. /*    1.01 - If we find out that a cancel has occurred, we won't exit to the
  423.     shell, but will return instead. */
  424.  
  425. #pragma segment Main
  426. static void Terminate (void)
  427. {
  428.     WindowPtr    aWindow;
  429.     Boolean        closed;
  430.     
  431.     closed = true;
  432.     do {
  433.         aWindow = FrontWindow();                /* get the current front window */
  434.         if (aWindow != nil)
  435.             closed = DoCloseWindow(aWindow);    /* close this window */    
  436.     }
  437.     while (closed && (aWindow != nil));
  438.     if (closed)
  439.         ExitToShell();                            /* exit if no cancellation */
  440. } /*Terminate*/
  441.  
  442. /*    This is called when an item is chosen from the menu bar (after calling
  443.     MenuSelect or MenuKey). It performs the right operation for each command.
  444.     It is good to have both the result of MenuSelect and MenuKey go to
  445.     one routine like this to keep everything organized. */
  446.  
  447. #pragma segment Main
  448. static void DoMenuCommand (long menuResult)
  449. {
  450.     short        menuID;                /* the resource ID of the selected menu */
  451.     short        menuItem;            /* the item number of the selected menu */
  452.     short        itemHit;
  453.     Str255        daName;
  454.     short        daRefNum;
  455.     Boolean        handledByDA;
  456.     Str255        password;
  457.  
  458.     menuID = HiWord(menuResult);    /* use macros for efficiency to... */
  459.     menuItem = LoWord(menuResult);    /* get menu item number and menu number */
  460.     switch ( menuID ) {
  461.         case mApple:
  462.             switch ( menuItem ) {
  463.                 case iAbout:        /* bring up alert for About */
  464.                     itemHit = Alert(rAboutAlert, nil);
  465.                     break;
  466.                 default:            /* all non-About items in this menu are DAs */
  467.                     /* type Str255 is an array in MPW 3 */
  468.                     GetMenuItemText(GetMenuHandle(mApple), menuItem, daName);
  469.                     daRefNum = OpenDeskAcc(daName);
  470.                     break;
  471.             }
  472.             break;
  473.         case mFile:
  474.             switch ( menuItem ) {
  475.                 case iClose:
  476.                     DoCloseWindow(FrontWindow());
  477.                     break;
  478.                 case iQuit:
  479.                     Terminate();
  480.                     break;
  481.             }
  482.             break;
  483.         case mEdit:                    /* call SystemEdit for DA editing & MultiFinder */
  484.             handledByDA = SystemEdit(menuItem-1);    /* since we don’t do any Editing */
  485.             break;
  486.         case mPassword:
  487.             switch ( menuItem ) {
  488.                 case iTwoItem:
  489.                     TwoItemDialog(password);
  490.                     break;
  491.                 case iDifferentFont:
  492.                     DifferentFontDialog(password);
  493.                     break;
  494.                 case iInternalBuffer:
  495.                     InternalBufferDialog(password);
  496.                     break;
  497.             }
  498.             DisplayPassword(password);
  499.             break;
  500.     }
  501.     HiliteMenu(0);                    /* unhighlight what MenuSelect (or MenuKey) hilited */
  502. } /*DoMenuCommand*/
  503.  
  504. /*    This is called when a mouse-down event occurs in the content of a window.
  505.     Other applications might want to call FindControl, TEClick, etc., to
  506.     further process the click. */
  507.  
  508. #pragma segment Main
  509. static void DoContentClick(WindowPtr    window)
  510. {
  511. #pragma unused (window)
  512. } /*DoContentClick*/
  513.  
  514. /*    This is called when a window is activated or deactivated.
  515.     In Sample, the Window Manager's handling of activate and
  516.     deactivate events is sufficient. Other applications may have
  517.     TextEdit records, controls, lists, etc., to activate/deactivate. */
  518.  
  519. #pragma segment Main
  520. static void DoActivate(WindowPtr window, Boolean becomingActive)
  521. {
  522.     if ( IsAppWindow(window) ) {
  523.         if ( becomingActive )
  524.             /* do whatever you need to at activation */ ;
  525.         else
  526.             /* do whatever you need to at deactivation */ ;
  527.     }
  528. } /*DoActivate*/
  529.  
  530. /* Draw the contents of the application window. We do some drawing in color, using
  531.    Classic QuickDraw's color capabilities. This will be black and white on old
  532.    machines, but color on color machines. At this point, the window’s visRgn
  533.    is set to allow drawing only where it needs to be done. */
  534.  
  535. #pragma segment Main
  536. static void DrawWindow(WindowPtr    window)
  537. {
  538.     SetPort(window);
  539.  
  540.     EraseRect(&window->portRect);    /* clear out any garbage that may linger */
  541. } /*DrawWindow*/
  542.  
  543. /*    This is called when an update event is received for a window.
  544.     It calls DrawWindow to draw the contents of an application window.
  545.     As an efficiency measure that does not have to be followed, it
  546.     calls the drawing routine only if the visRgn is non-empty. This
  547.     will handle situations where calculations for drawing or drawing
  548.     itself is very time-consuming. */
  549.  
  550. #pragma segment Main
  551. static void DoUpdate(WindowPtr    window)
  552. {
  553.     if ( IsAppWindow(window) ) {
  554.         BeginUpdate(window);                /* this sets up the visRgn */
  555.         if ( ! EmptyRgn(window->visRgn) )    /* draw if updating needs to be done */
  556.             DrawWindow(window);
  557.         EndUpdate(window);
  558.     }
  559. } /*DoUpdate*/
  560.  
  561. /* Do the right thing for an event. Determine what kind of event it is, and call
  562.  the appropriate routines. */
  563.  
  564. #pragma segment Main
  565. static void DoEvent (EventRecord    *event)
  566. {
  567.     short        part, err;
  568.     WindowPtr    window;
  569.     Boolean        hit;
  570.     char        key;
  571.     Point        aPoint;
  572.  
  573.     switch ( event->what ) {
  574.         case mouseDown:
  575.             part = FindWindow(event->where, &window);
  576.             switch ( part ) {
  577.                 case inMenuBar:                /* process a mouse menu command (if any) */
  578.                     AdjustMenus();
  579.                     DoMenuCommand(MenuSelect(event->where));
  580.                     break;
  581.                 case inSysWindow:            /* let the system handle the mouseDown */
  582.                     SystemClick(event, window);
  583.                     break;
  584.                 case inContent:
  585.                     if ( window != FrontWindow() ) {
  586.                         SelectWindow(window);
  587.                         /*DoEvent(event);*/    /* use this line for "do first click" */
  588.                     } else
  589.                         DoContentClick(window);
  590.                     break;
  591.                 case inDrag:                /* pass screenBits.bounds to get all gDevices */
  592.                     DragWindow(window, event->where, &qd.screenBits.bounds);
  593.                     break;
  594.                 case inGrow:
  595.                     break;
  596.                 case inZoomIn:
  597.                 case inZoomOut:
  598.                     hit = TrackBox(window, event->where, part);
  599.                     if ( hit ) {
  600.                         SetPort(window);                /* the window must be the current port... */
  601.                         EraseRect(&window->portRect);    /* because of a bug in ZoomWindow */
  602.                         ZoomWindow(window, part, true);    /* note that we invalidate and erase... */
  603.                         InvalRect(&window->portRect);    /* to make things look better on-screen */
  604.                     }
  605.                     break;
  606.             }
  607.             break;
  608.         case keyDown:
  609.         case autoKey:                        /* check for menukey equivalents */
  610.             key = event->message & charCodeMask;
  611.             if ( event->modifiers & cmdKey )            /* Command key down */
  612.                 if ( event->what == keyDown ) {
  613.                     AdjustMenus();                        /* enable/disable/check menu items properly */
  614.                     DoMenuCommand(MenuKey(key));
  615.                 }
  616.             break;
  617.         case activateEvt:
  618.             DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
  619.             break;
  620.         case updateEvt:
  621.             DoUpdate((WindowPtr) event->message);
  622.             break;
  623.         /*    1.01 - It is not a bad idea to at least call DIBadMount in response
  624.             to a diskEvt, so that the user can format a floppy. */
  625.         case diskEvt:
  626.             if ( HiWord(event->message) != noErr ) {
  627.                 SetPt(&aPoint, kDILeft, kDITop);
  628.                 err = DIBadMount(aPoint, event->message);
  629.             }
  630.             break;
  631.         case kOSEvent:
  632.         {
  633.         /*    1.02 - must BitAND with 0x0FF to get only low byte */
  634.             switch ((event->message >> 24) & 0x0FF) {        /* high byte of message */
  635.                 case kSuspendResumeMessage:        /* suspend/resume is also an activate/deactivate */
  636.                     gInBackground = (event->message & kResumeMask) == 0;
  637.                     DoActivate(FrontWindow(), !gInBackground);
  638.                     break;
  639.             }
  640.             break;
  641.         }    
  642.     }
  643. } /*DoEvent*/
  644.  
  645. /*    Get events forever, and handle them by calling DoEvent.
  646.     Get the events by calling WaitNextEvent, if it's available, otherwise
  647.     by calling GetNextEvent. Also call AdjustCursor each time through the loop. */
  648.  
  649. #pragma segment Main
  650. static void EventLoop(void)
  651. {
  652.     RgnHandle    cursorRgn;
  653.     Boolean        gotEvent;
  654.     EventRecord    event;
  655.     Point        mouse;
  656.  
  657.     cursorRgn = NewRgn();            /* we’ll pass WNE an empty region the 1st time thru */
  658.     do {
  659.         /* use WNE if it is available */
  660.         if ( gHasWaitNextEvent ) {
  661.             GetGlobalMouse(&mouse);
  662.             AdjustCursor(mouse, cursorRgn);
  663.             gotEvent = WaitNextEvent(everyEvent, &event, LONG_MAX, cursorRgn);
  664.         }
  665.         else {
  666.             SystemTask();
  667.             gotEvent = GetNextEvent(everyEvent, &event);
  668.         }
  669.         if ( gotEvent ) {
  670.             /* make sure we have the right cursor before handling the event */
  671.             AdjustCursor(event.where, cursorRgn);
  672.             DoEvent(&event);
  673.         }
  674.         /*    If you are using modeless dialogs that have editText items,
  675.             you will want to call IsDialogEvent to give the caret a chance
  676.             to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  677.             for a non-NIL value before calling IsDialogEvent. */
  678.     } while ( true );    /* loop forever; we quit via ExitToShell */
  679. } /*EventLoop*/
  680.  
  681. #pragma segment Main
  682. void main(void)
  683. {
  684.     #ifdef applec
  685.         UnloadSeg((Ptr) _DataInit);        /* note that _DataInit must not be in Main! */
  686.     #endif
  687.     
  688.     /* 1.01 - call to ForceEnvirons removed */
  689.     
  690.     /*    If you have stack requirements that differ from the default,
  691.         then you could use SetApplLimit to increase StackSpace at 
  692.         this point, before calling MaxApplZone. */
  693.     MaxApplZone();                    /* expand the heap so code segments load at the top */
  694.  
  695.     Initialize();                    /* initialize the program */
  696.     UnloadSeg((Ptr) Initialize);    /* note that Initialize must not be in Main! */
  697.  
  698.     EventLoop();                    /* call the main event loop */
  699. }
  700.  
  701. /**************************************************************************************
  702. *** 1.01 DoCloseBehind(window) was removed ***
  703.  
  704.     1.01 - DoCloseBehind was a good idea for closing windows when quitting
  705.     and not having to worry about updating the windows, but it suffered
  706.     from a fatal flaw. If a desk accessory owned two windows, it would
  707.     close both those windows when CloseDeskAcc was called. When DoCloseBehind
  708.     got around to calling DoCloseWindow for that other window that was already
  709.     closed, things would go very poorly. Another option would be to have a
  710.     procedure, GetRearWindow, that would go through the window list and return
  711.     the last window. Instead, we decided to present the standard approach
  712.     of getting and closing FrontWindow until FrontWindow returns NIL. This
  713.     has a potential benefit in that the window whose document needs to be saved
  714.     may be visible since it is the front window, therefore decreasing the
  715.     chance of user confusion. For aesthetic reasons, the windows in the
  716.     application should be checked for updates periodically and have the
  717.     updates serviced.
  718. **************************************************************************************/
  719.